<?php

namespace app\system\controller;

use app\common\model\AuthRuleModel;

class AuthRuleController extends BaseController
{
  /**
   * 不需要登陆的方法
   * @var array
   */
  protected $noLogin = [];

  /**
   * 不检测权限方法
   * @var array
   */
  protected $noCheck = [];

  /**
   * 权限映射
   * @var array
   */
  protected $mapCheck = [
    "*" => "AuthGroup/index"
  ];
  /**
   * 当前模型
   * @var null
   */
  protected $model = null;

  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->model = new AuthRuleModel();
  }

  /**
   * 首页
   * @return mixed
   * @throws \Exception
   */
  public function index()
  {
    $list = $this->model->getList(true);
    $this->assign('list', $list);
    return $this->fetch();
  }

  /**
   * 添加规则
   * @return string
   * @throws \Exception
   */
  public function add()
  {
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      $this->validate($data, [
        'title|规则名称' => 'require',
        'name|规则名称' => 'require'
      ]);
      $this->model->add($data);
      $this->success('操作成功');
    }
    $list = $this->model->getList();
    $this->assign('list',$list);
    return $this->fetch();
  }

  /**
   * 修改规则
   * @return string
   * @throws \Exception
   */
  public function edit()
  {
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      $this->validate($data, [
        'id|规则标识' => 'number',
        'title|规则名称' => 'require',
        'name|规则名称' => 'require'
      ]);
      $this->model->edit($data);
      $this->success('操作成功');
    }
    $id = $this->request->param('id/d');
    $info = $this->model->where('id', $id)->find();
    $list = $this->model->getList();
    $list = format_tree_select($list, $list[$id]['path']);
    $this->assign('list',$list);
    $this->assign('info', $info);
    return $this->fetch();
  }

  /**
   * 修改状态
   * @throws \Exception
   */
  public function set()
  {
    $id = $this->request->param('id/d');
    $info = $this->model->where('id', $id)->find();
    $status = $info['status'] ? 0 : 1;
    $this->model->where('id', $id)->update(['status' => $status]);
    $this->success('操作成功');
  }

  /**
   * 刷新缓存
   * @throws \Exception
   */
  public function refresh()
  {
    $this->model->getList(true);
    $this->success('操作成功');
  }

  /**
   * 删除
   * @throws \Exception
   */
  public function del()
  {
    $id = $this->request->param('id/d');
    $this->model->del($id);
    $this->success('操作成功');
  }
}
